<template>
  <a-card>
    <a-button
        type="primary"
        style="margin: 20px 0 50px 0"
        @click="handleAdd"
    >
      添加用户
    </a-button>
    <a-table
        :loading="loading"
        :columns="columns"
        :data-source="list"
        :pagination="pagination"
        @change="handleChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userType'">
          {{ $filters.dictText(record.userType, 'USER_TYPE') }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          {{ $filters.dictText(record.status, 'USER_STATUS') }}
        </template>
        <template v-if="column.dataIndex === 'action'">
          <a-popconfirm
              key="remove"
              title="确定删除吗?"
              ok-text="是"
              cancel-text="否"
              @confirm="handleRemove(record)"
          >
            <a href="javascript:void(0)" style="color:red">
              <delete-outlined style="margin-right: 5px;"/>
              删除
            </a>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <choose-user-form
        ref="chooseUserFormRef"
        @ok="loadData"
    />
  </a-card>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { PageParam } from '@/config/common'
import { getUsers } from '@/api/sys-user'
import { DeleteOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import ChooseUserForm from '@/page/system/role/modules/ChooseUserForm.vue'
import { deleteUserRole } from '@/api/sys-role'
import { usePagination } from '@/modules/use-modules'

const chooseUserFormRef = ref<InstanceType<typeof ChooseUserForm>>()

const props = defineProps({
  roleId: String
})

watch(() => props.roleId,
  (count, prevCount) => {
    loadData()
  })

const columns = [
  {
    title: '账号',
    dataIndex: 'username'
  },
  {
    title: '昵称',
    dataIndex: 'nickName'
  },
  {
    title: '状态',
    dataIndex: 'status'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px'
  }
]
const {
  pagination,
  loading,
  list,
  handleChange,
  loadData
} = usePagination<any>((page: PageParam) => {
  return getUsers(page, { roleId: props.roleId })
})

const handleRemove = async (record: any) => {
  if (props.roleId) {
    await deleteUserRole(record.id, props.roleId)
    message.info('删除成功')
    loadData()
  }
}

const handleAdd = () => {
  chooseUserFormRef.value.open(props.roleId)
}

loadData()
</script>
